//
//  RTComposeView.swift
//  Weibo
//
//  Created by Brisinga on 16/3/11.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit
import pop

class RTComposeView: UIView {
    
    
    // 控制器
    var target = UIViewController()
    
    
    // 按钮数组
    private var btnArr: [RTComposeButton] = [RTComposeButton]()
    
  // 初始化
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        // 加载内部控件
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 加载内部组件
    private func setupUI() {
        
        frame = UIScreen.mainScreen().bounds
        
        // 磨砂的背景图
        let bgImage = UIImageView(image: getShot().applyLightEffect())
        
        addSubview(bgImage)
        
        // 添加广告语
        addSubview(sloganView)
        
        // 布局
        sloganView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            
            make.top.equalTo(self).offset(100)
        }
        
        addChildButtons()
    }
    
    
    
    // 添加按钮
    private func addChildButtons() {
    
        let itemW: CGFloat = 80
        let itemH: CGFloat = 110
        
        let itemMargin = (kScreenWidth - itemW * 3)/4
        
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        
        let tempArr = NSArray(contentsOfFile: path)!
        
        var menInfos = [RTComposeModel]()
        
        for dict in tempArr {
        
            let info = RTComposeModel(dict: dict as! [String: AnyObject])
            
            menInfos.append(info)
        }
        
        for (i,info) in menInfos.enumerate() {
        
            let btn = RTComposeButton()
            
            // 添加按钮点击事件
            btn.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            btn.tag = i
            
            btn.menInfo = info
            
            btn.frame.size = CGSizeMake(itemW, itemH)
            
            addSubview(btn)
            
            btnArr.append(btn)
            
            let col = i % 3
            let colum = i / 3
            
            btn.frame.origin.x = CGFloat(col + 1) * itemMargin + CGFloat(col) * itemW
            btn.frame.origin.y = CGFloat(colum) * (itemMargin + itemH) + kScreenHeight
            
            
        }
    
    
    }
    
    // 添加控制器
    func show (target: UIViewController) {
        
        target.view.addSubview(self)
        
        self.target = target
    }
    
    // 按钮动画
    private func buttonsAnimation(isUp: Bool) {
    
        let tempArr = isUp ? btnArr : btnArr.reverse()
        
        for (index,value) in tempArr.enumerate() {
        
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            animation.toValue = NSValue(CGPoint:CGPoint(x: value.center.x, y: value.center.y + (isUp ? -300 : +300)))
            
            animation.springBounciness = 10
            
            animation.springSpeed = 8
            
            animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            
            value.pop_addAnimation(animation, forKey: nil)
        }
    }
    
    // 收回按钮
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        buttonsAnimation(false)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64((0.4 * Double(NSEC_PER_SEC)))), dispatch_get_main_queue(), {
            self.removeFromSuperview()
        });
    }
    
    
    override func didMoveToSuperview() {
        
        buttonsAnimation(true)
    }
    
    
    // 按钮点击事件
    @objc private func composeButtonClick(button: RTComposeButton) {
    button.alpha = 0.1
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.btnArr{
                
                value.alpha = 0.01
                
                value.transform = value == button ?  CGAffineTransformMakeScale(2, 2) :  CGAffineTransformMakeScale(0.01, 0.01)
            }
            
            }) { (_) -> Void in
                
                print("haha")
                let menInfo = button.menInfo
                
                let targetClass = NSClassFromString((menInfo!.targetVC)!) as! RTComposeViewController.Type
                
                let vc = targetClass.init()
                
                
                self.target.presentViewController(RTNavgationController(rootViewController: vc), animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()
                })
        }
    
    }
    
    
    // 移除
    deinit {
        
        print("我移除了")
    }
    
    
    // 截取屏幕
    private func getShot()->UIImage {
    
        let rect = UIScreen.mainScreen().bounds
        
        let window = UIApplication.sharedApplication().keyWindow
        
        // 开启图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        
        window?.drawViewHierarchyInRect(rect, afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image
    }
    
    
    // 懒加载控件
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))

}





